import {Button, Card, Col, Drawer, Form, Input, InputNumber, message, Radio, Row, Slider, Space, Tooltip} from "antd";
import './index.less'
import React, {useState} from "react";
import {CopyOutlined, DownloadOutlined, HighlightOutlined, SettingOutlined} from "@ant-design/icons";
import {baseURL} from "../../utils/request.js";
import {useLocation} from "react-router-dom";
import ReactMarkdown from "react-markdown";

const {TextArea} = Input;

const marks = {
    0: '轻度',
    50: '中度',
    100: {
        style: {
            color: '#f50',
        },
        label: <strong>强度</strong>,
    },
};

const TextPolishing = () => {

    const {state} = useLocation()

    // 未精修的文本数据
    const [unmodifiedText, setUnmodifiedText] = useState(state?.text || '')


    // 修改未精修的文本数据
    const changeUnmodifiedText = (e) => {
        // console.log(e.target.value)
        setUnmodifiedText(e.target.value)
    }

    // 精修后的文本数据
    const [modifiedText, setModifiedText] = useState('')

    // 修改精修后的文本数据
    // const changeModifiedText = (e) => {
    //     setModifiedText(e.target.value)
    // }
    // 复制功能
    const copyText = () => {

        navigator.clipboard.writeText(modifiedText)
            .then(() => {
                console.log('复制成功');
                message.success('复制成功👻')
            })
            .catch(err => {
                console.error('复制失败', err);
                message.error('复制失败🤷‍♂️',);
            })
    }

    // 生成txt文件保存本地
    const saveText = () => {
// 要保存的字符串
        const stringData = modifiedText
        // dada 表示要转换的字符串数据，type 表示要转换的数据格式
        const blob = new Blob([stringData], {
            type: "text/plain;charset=utf-8"
        })
        // 根据 blob生成 url链接
        const objectURL = URL.createObjectURL(blob)

        // 创建一个 a 标签Tag
        const aTag = document.createElement('a')
        // 设置文件的下载地址
        aTag.href = objectURL
        // 设置保存后的文件名称
        aTag.download = 'FusionMind' + new Date().getFullYear().toString() + new Date().getMonth().toString() + new Date().getDay().toString() + new Date().getTime().toString() + ".txt"
        // 给 a 标签添加点击事件
        aTag.click()
        // 释放一个之前已经存在的、通过调用 URL.createObjectURL() 创建的 URL 对象。
        // 当你结束使用某个 URL 对象之后，应该通过调用这个方法来让浏览器知道不用在内存中继续保留对这个文件的引用了。
        URL.revokeObjectURL(objectURL)
    }

    // 抽屉打开状态
    const [isOpenDrawer, setIsOpenDrawer] = useState(false)

    // 精修风格配置项
    const modifiedStyleOptions = [
        {
            label: '正式',
            value: '正式',
        },
        {
            label: '专业',
            value: '专业',
        },
        {
            label: '客观',
            value: '客观',
        },
        {
            label: '礼貌',
            value: '礼貌',
        },
        {
            label: '简洁',
            value: '简洁',
        },
        {
            label: '严肃',
            value: '严肃',
        },
        {
            label: '清晰',
            value: '清晰',
        },
        {
            label: '冷静',
            value: '冷静',
        },
        {
            label: '谦虚',
            value: '谦虚',
        },
        {
            label: '口语',
            value: '口语',
        },
        {
            label: '轻松',
            value: '轻松',
        },
        {
            label: '优雅',
            value: '优雅',
        },
        {
            label: '自信',
            value: '自信',
        },
        {
            label: '热情',
            value: '热情',
        },
        {
            label: '感性',
            value: '感性',
        },
        {
            label: '幽默',
            value: '幽默',
        },
        {
            label: '讽刺',
            value: '讽刺',
        },
        {
            label: '创意',
            value: '创意',
        },
    ];

    // 选择的精修风格
    const [modifiedStyle, setModifiedStyle] = useState('')

    // 选择精修风格
    const changeModifiedStyle = (e) => {
        setModifiedStyle(e.target.value)
    };

    // 字数要求
    const [fontNumber, setFontNumber] = useState(100)
    // 修改字数要求
    const changeFontNumber = (e) => {
        setFontNumber(e)
    }

    // 感情基调
    const [emotionalTone, setEmotionalTone] = useState('')

    // 修改感情基调
    const changeEmotionalTone = (e) => {
        setEmotionalTone(e.target.value)
    }

    // 精修强度
    const [modifiedLevel, setModifiedLevel] = useState('')
    // 修改精修强度
    const changeModifiedLevel = (e) => {
        // setModifiedLevel(e.target.value)
        // console.log(e)
        switch (e) {
            case 0:
                setModifiedLevel('轻度')
                break
            case 50:
                setModifiedLevel('中度')
                break
            case 100:
                setModifiedLevel('强度')
                break
            default:
                break
        }
    }

    // 开始精修
    const startModify = async () => {
        let obj = {
            unmodifiedText,
            modifiedLevel,
            modifiedStyle,
            emotionalTone,
            fontNumber
        }
        console.log(obj)
        setModifiedStatus(true)


        let localData = window.localStorage.getItem('polishingHistory')

        let arr = []
        if (localData) {
            arr = JSON.parse(localData)
            if (arr.length >= 5) {
                arr.shift()
            }
            arr.push(obj)

        } else {
            arr.push(obj)
        }

        const resp = await fetch(baseURL + '/api/v1/chat/article/edit', {
            method: 'post',
            headers: {
                'Content-Type': 'application/json;charset=utf-8',
                Authorization: window.localStorage.getItem('token'),
                // Authorization: 'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJvb2lZWTZXMW1TUUpLYXFXVGxzd2hkYXdHeXBnIiwib3BlbklkIjoib29pWVk2VzFtU1FKS2FxV1Rsc3doZGF3R3lwZyIsImV4cCI6MTcxNDQ2MDkzMiwidXNlcklkIjoiMzY3NDQ2NDI3NTI3Mjg2Nzg0IiwiaWF0IjoxNzEzODU2MTMyLCJqdGkiOiI3ZmE3YjllZS1jZjlhLTQ5YzQtOWEzMS1mMWQzNGU5M2I3ZmEifQ.5eFcsrK62ASy8ecogKBTek6TgEQsn8pOjUcue9sGI90'
            },
            body: JSON.stringify(
                {
                    model: window.localStorage.getItem('gpt'),
                    messages: arr,
                    controller: "false"
                }
            )
        })

        const reader = resp.body.getReader()

        let tempModifiedText = ''
        const textDecoder = new TextDecoder()
        while (1) {
            const {done, value} = await reader.read()
            if (done) {
                break
            }
            const str = textDecoder.decode(value)


            tempModifiedText += str
            console.log('精修文章', tempModifiedText)
            setModifiedText(tempModifiedText)
        }

        setModifiedStatus(false)
        saveToLocal(obj)
    }

    //     将数据保存本地
    const saveToLocal = (formData) => {

        let polishingHistory = window.localStorage.getItem('polishingHistory')
        if (polishingHistory) {
            let arr = JSON.parse(polishingHistory)
            if (arr.length === 5) {
                arr.shift()
            }
            arr.push(formData)

            console.log(arr)
            window.localStorage.setItem('polishingHistory', JSON.stringify(arr))
        } else {
            let arr = []
            arr.push(formData)
            console.log(arr)
            window.localStorage.setItem('polishingHistory', JSON.stringify(arr))
        }
    }


    // 精修状态
    const [modifiedStatus, setModifiedStatus] = useState(false)


    return (
        <>
            {/*精修设置抽屉*/}
            <Drawer title="精修设置" placement={'top'} open={isOpenDrawer} onClose={() => setIsOpenDrawer(false)}>
                <Form
                    layout={'vertical'}
                    className={'myform'}
                >
                    <Form.Item label="修改风格">
                        <Radio.Group
                            options={modifiedStyleOptions}
                            onChange={changeModifiedStyle}
                            optionType="button"/>
                    </Form.Item>

                    <Form.Item label="感情基调"
                               style={{display: 'flex', alignItems: 'center', justifyContent: 'flex-start'}}>
                        <Radio.Group
                            defaultValue={""}
                            size="middle"
                            onChange={changeEmotionalTone}
                        >
                            <Radio.Button value="欢快">欢快</Radio.Button>
                            <Radio.Button value="忧愁">忧愁</Radio.Button>
                            <Radio.Button value="寂寞">寂寞</Radio.Button>
                            <Radio.Button value="伤感">伤感</Radio.Button>
                            <Radio.Button value="恬淡">恬淡</Radio.Button>
                            <Radio.Button value="闲适">闲适</Radio.Button>
                            <Radio.Button value="激愤">激愤</Radio.Button>
                            <Radio.Button value="思念">思念</Radio.Button>
                        </Radio.Group>

                        <div style={{margin: '10px 0'}}>
                            自定义添加:
                            <Input
                                onChange={changeEmotionalTone}
                                style={{
                                    width: 100,
                                    marginLeft: 10,
                                }}
                            />
                        </div>
                    </Form.Item>

                    <Tooltip title="字数必须在100-1500字哦👻">
                        <Form.Item label="字数要求" style={{width: 100}}>
                            <InputNumber value={fontNumber} onChange={changeFontNumber} min={100} max={1500}
                                         addonAfter="字"
                                         defaultValue={100}/>
                        </Form.Item>
                    </Tooltip>

                </Form>
            </Drawer>

            <Card
                title="文章精修"
                bordered={false}
                style={{
                    width: '100%',

                }}
            >
                <Row gutter={10}>
                    <Col span={10}>
                        <Card
                            bordered={false}
                            title="未精修文本"
                            className={'leftCard'}
                            style={{
                                width: '100%',

                            }}
                        >
                            <TextArea
                                value={unmodifiedText}
                                allowClear
                                showCount
                                maxLength={3000}
                                onChange={changeUnmodifiedText}
                                placeholder="输入待精修文本"
                                style={{
                                    height: 300,
                                    resize: 'none',
                                }}
                            />

                            <div style={{display: 'flex', flexDirection: 'column', alignItems: 'flex-start'}}>
                                <div style={{
                                    marginLeft: '15%',
                                    fontSize: 'large',
                                    fontWeight: 'bold',
                                    marginTop: 10
                                }}>
                                    精修强度
                                </div>
                                <Slider style={{width: '70%', marginLeft: '15%', marginRight: '15%'}} marks={marks}
                                        step={null} defaultValue={0} onChange={changeModifiedLevel}/>
                            </div>

                            <Row justify={"space-around"} style={{marginTop: 20}}>
                                <Col span={4}>
                                    <Button type="primary" onClick={() => setIsOpenDrawer(true)}>
                                        <SettingOutlined/>
                                        精修设置
                                    </Button>
                                </Col>
                                <Col span={4}>
                                    <Button loading={modifiedStatus} type="primary" onClick={startModify}>
                                        <HighlightOutlined/>
                                        开始精修
                                    </Button>
                                </Col>
                            </Row>

                        </Card>
                    </Col>
                    <Col span={14}>
                        <Card
                            bordered={false}
                            title={'精修结果'}
                            className={'leftCard'}
                            style={{
                                width: '100%',
                                height: '72vh'
                            }}
                        >

                            <div style={{
                                height: 300,
                                overflow: "auto"
                            }}>
                                <ReactMarkdown style={{
                                    height: '300px',
                                }}>
                                    {modifiedText}
                                </ReactMarkdown>
                            </div>

                            {/*<TextArea*/}
                            {/*    allowClear*/}
                            {/*    showCount*/}
                            {/*    value={modifiedText}*/}
                            {/*    onChange={changeModifiedText}*/}
                            {/*    placeholder="精修结果"*/}
                            {/*    style={{*/}
                            {/*        height: 300,*/}
                            {/*        resize: 'none',*/}
                            {/*    }}*/}
                            {/*/>*/}

                            <Space style={{marginTop: 20}}>
                                <Button type={'primary'} onClick={copyText}>
                                    <CopyOutlined/>
                                </Button>

                                <Button type={'primary'} onClick={saveText}>
                                    <DownloadOutlined/>
                                    保存到本地
                                </Button>
                            </Space>
                        </Card>
                    </Col>
                </Row>
            </Card>
        </>
    )
}

export default TextPolishing
